/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.cloud.business.usercenter.resolver;

import cn.hutool.core.util.StrUtil;
import com.lvyh.lightframe.cloud.business.usercenter.service.SysUserService;
import com.lvyh.lightframe.cloud.common.annotation.CurrentUser;
import com.lvyh.lightframe.cloud.common.constant.SystemConstants;
import com.lvyh.lightframe.cloud.common.model.SysRole;
import com.lvyh.lightframe.cloud.common.model.SysUser;
import com.lvyh.lightframe.cloud.common.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Token转化SysUser
 * 自定义方法参数解析器，取出request中的user，并赋值给添加了@CurrentUser注解的参数user。
 */
@Slf4j
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(CurrentUser.class)
                && methodParameter.getParameterType().isAssignableFrom(SysUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) {
        CurrentUser currentUser = methodParameter.getParameterAnnotation(CurrentUser.class);
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String userId = request.getHeader(SystemConstants.USER_ID_HEADER);
        String username = request.getHeader(SystemConstants.USER_HEADER);
        String roles = request.getHeader(SystemConstants.ROLE_HEADER);
        if (StrUtil.isBlank(username)) {
            log.warn("resolve argument error, username is empty.");
            return null;
        }
        SysUserService sysUserService = (SysUserService) SpringContextUtil.getBean(SysUserService.class);
        SysUser user = null;
        try {
            user = sysUserService.selectByUsername(username);
            List<SysRole> sysRoleList = new ArrayList<>();
            Arrays.stream(roles.split(",")).forEach(role -> {
                SysRole sysRole = new SysRole();
                sysRole.setCode(role);
                sysRoleList.add(sysRole);
            });
            user.setRoles(sysRoleList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return user;
    }
}
